package com.hadoop.mapreduce.TextIndex;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * 倒排索引的实现步骤一
 *
 *  a.txt
 *  hello tom
 *  hello jerry
 *  hello tom
 *
 *  b.txt
 *  hello jerry
 *  hello jerry
 *  tom jerry
 *
 *  c.txt
 *  hello jerry
 *  hello tom
 *
 *  目标：
 *  hello   a.txt-->3   b.txt-->2   c.txt-->2
 *  jerry   a.txt-->2   b.txt-->3   c.txt-->1
 *  tom     a.txt-->2   b.txt-->1   x.txt-->1
 */

public class TextIndexOne {
    static class TextIndexOneMapper extends Mapper<IntWritable,Text,Text,IntWritable>{
        Text k=new Text();
        IntWritable v=new IntWritable(1);
        @Override
        protected void map(IntWritable key, Text value, Context context) throws IOException, InterruptedException {
            FileSplit fileSplit = (FileSplit) context.getInputSplit();
            String fileName  = fileSplit.getPath().getName();
            String[] line = value.toString().split(" ");
            for (String word :
                    line) {
                k.set(word+"-"+fileName);
                context.write(k,v);
            }
        }
    }
    static class TextIndexOneReducer extends Reducer<Text,IntWritable,Text,IntWritable>{
        IntWritable intWritable=new IntWritable();
        @Override
        protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
            int count=0;
            for (IntWritable i :
                    values) {
                count+=i.get();
            }
            intWritable.set(count);
            context.write(key,intWritable);
        }
    }
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.set("mapred.textoutputformat.separator", ":");
        Job job = Job.getInstance(conf);
        job.setJarByClass(TextIndexOne.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        FileInputFormat.setInputPaths(job, new Path("D:/srcdata/inverindexinput"));
        FileOutputFormat.setOutputPath(job, new Path("D:/temp/out"));
        // FileInputFormat.setInputPaths(job, new Path(args[0]));
        // FileOutputFormat.setOutputPath(job, new Path(args[1]));

        job.setMapperClass(TextIndexOneMapper.class);
        job.setReducerClass(TextIndexOneReducer.class);

        job.waitForCompletion(true);

    }
}
